package cn.tnar.parkservice.controller.system;


import cn.tnar.parkservice.model.dto.AcctBasePhotoDto;
import cn.tnar.parkservice.model.dto.OssAliyunField;
import cn.tnar.parkservice.model.dto.ResultDataDto;
import cn.tnar.parkservice.model.response.AliOSSFiles;
import cn.tnar.parkservice.model.response.AliOssResponse;
import cn.tnar.parkservice.service.PicToParkInfoService;
import cn.tnar.parkservice.util.FileUtils;
import cn.tnar.parkservice.util.HouseUtil;
import cn.tnar.parkservice.util.OssAliyunUtil;
import cn.tnar.parkservice.util.base64ToMultipart;
import cn.tnar.parkservice.util.common.ResultJson;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

//import net.coobird.thumbnailator.Thumbnails;

/**
 * @Author: 陈亮
 * @Date: 2018/9/26 10:29
 */
@Api(tags = "阿里OSS文件管理")
@RestController
@RequestMapping("oss")

public class AliOssController {

    @Value("${oss.aliyun.bucket}")
    private String bucket;

    @Value("${oss.aliyun.endpoint}")
    private String endpoint;

    @Value("${oss.aliyun.host}")
    private String host;

    @Value("${oss.aliyun.accessId}")
    private String accessId;

    @Value("${oss.aliyun.accessKey}")
    private String accessKey;

    @Value("${oss.aliyun.key.parkimg}")
    private String keyParkImage;

    @Value("${oss.aliyun.filehost}")
    private String fileHost;

    @Value("${oss.aliyun.prefix}")
    private String prefix;

    @Autowired
    private OssAliyunUtil ossAliyunUtil;

    @Autowired
    private PicToParkInfoService picToParkInfoService;


    private ResultJson json = new ResultJson();

    private static final Logger log = LoggerFactory.getLogger(AliOssController.class);

    //    AliOssResponse
    @PostMapping("upload")
    public ResultJson upload(@RequestParam("file") MultipartFile file) {
        String fileUrl = null;
        long fileSize = file.getSize();
        try {
            if (null != file) {
                OssAliyunField ossAliyunField = new OssAliyunField();
                ossAliyunField.setAccessKeyId(accessId);
                ossAliyunField.setAccessKeySecret(accessKey);
                ossAliyunField.setBucketName(bucket);
                ossAliyunField.setEndPoint(endpoint);
                ossAliyunField.setPrefix(prefix);
                fileUrl = ossAliyunUtil.upload(ossAliyunField, file);
                if (fileUrl != null && !"".equals(fileUrl)) {
                    AliOssResponse aliOssResponse = new AliOssResponse();
                    aliOssResponse.setSize(fileSize);
                    aliOssResponse.setUrl(fileUrl);

                    json.setData(aliOssResponse).setCode(200).setMsg("success");
                } else {
                    json.setData(null).setCode(200).setMsg("fail");
                }
            } else {
                json.setData(null).setCode(200).setMsg("fail");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return json;
    }

    @PostMapping("uploads")
    public ResultJson uploads(@RequestParam("files") MultipartFile[] files) {
        List<AliOssResponse> imgUrlList = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileUrl = null;
            long fileSize = file.getSize();
            try {
                if (null != file) {
                    OssAliyunField ossAliyunField = new OssAliyunField();
                    ossAliyunField.setAccessKeyId(accessId);
                    ossAliyunField.setAccessKeySecret(accessKey);
                    ossAliyunField.setBucketName(bucket);
                    ossAliyunField.setEndPoint(endpoint);
                    ossAliyunField.setPrefix(prefix);
                    fileUrl = ossAliyunUtil.upload(ossAliyunField, file);
                    if (fileUrl != null && !"".equals(fileUrl)) {
                        AliOssResponse aliOssResponse = new AliOssResponse();
                        aliOssResponse.setSize(fileSize);
                        aliOssResponse.setUrl(fileUrl);
                        imgUrlList.add(aliOssResponse);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (imgUrlList.size() > 0) {
            json.setData(imgUrlList).setCode(200).setMsg("success");

        } else {
            json.setData(null).setCode(900).setMsg("success");
        }

        return json;
    }


    @ApiOperation(value = "从OSS服务器获取前缀为'beijing'目录中的所有文件(目前不用)")
    @GetMapping("queryOSS")
    public ResultJson queryOSS() {
        OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey);
        List<AliOSSFiles> filelist = new ArrayList<>();
        final int maxKeys = 200;
        String nextMarker = null;
        ObjectListing objectListing;
        do {
            objectListing = ossClient.listObjects(new ListObjectsRequest(bucket).withMarker(nextMarker).withMaxKeys(maxKeys).withPrefix(prefix));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                AliOSSFiles aliOSSFiles = new AliOSSFiles("http://parkingoss.oss.aliyuncs.com/" + s.getKey(), s.getSize(), s.getLastModified());
                filelist.add(aliOSSFiles);
            }
            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());
        ossClient.shutdown();
        return json.setData(filelist).setCode(200).setMsg("success");
    }


    @PostMapping("uploadPic")
    public ResultJson uploadPic(@RequestBody String base64) {
        MultipartFile file = base64ToMultipart.base64ToMultipart(base64);

        String fileUrl = null;
        long fileSize = file.getSize();
        try {
            if (null != file) {
                OssAliyunField ossAliyunField = new OssAliyunField();
                ossAliyunField.setAccessKeyId(accessId);
                ossAliyunField.setAccessKeySecret(accessKey);
                ossAliyunField.setBucketName(bucket);
                ossAliyunField.setEndPoint(endpoint);
                ossAliyunField.setPrefix(prefix);
                fileUrl = ossAliyunUtil.upload(ossAliyunField, file);
                if (fileUrl != null && !"".equals(fileUrl)) {
                    AliOssResponse aliOssResponse = new AliOssResponse();
                    aliOssResponse.setSize(fileSize);
                    aliOssResponse.setUrl(fileUrl);

                    json.setData(aliOssResponse).setCode(200).setMsg("success");
                } else {
                    json.setData(null).setCode(200).setMsg("fail");
                }
            } else {
                json.setData(null).setCode(200).setMsg("fail");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return json;
    }


    @ApiOperation("上传并保存数据库（停车场封面、详情图）")
    @PostMapping("/uploadFileToOosNew")
    public ResultJson uploadFileToOosNew(@RequestParam("file") MultipartFile file, @RequestParam String parkCode, @RequestParam int num, @RequestParam int fileType) {

        ResultJson upload = upload(file);
        if (upload.getData() == null) {
            return json.setData(null).setCode(900).setMsg("上传失败");
        }

        AliOssResponse data = (AliOssResponse) upload.getData();
        String url = data.getUrl();

        if (url != null && !url.equals("")) {
            AliOssResponse aliOssResponse = new AliOssResponse();
            aliOssResponse.setSize(file.getSize());
            aliOssResponse.setUrl(url);
            int ret = 0;

            if (num == 1) {
                ret = picToParkInfoService.insertPicToParkInfo(url, parkCode);
            }
            if (num == 2) {
                int objectId = picToParkInfoService.selectId(parkCode);
                AcctBasePhotoDto dto = new AcctBasePhotoDto();
                dto.setObjectId(objectId);
                dto.setFileType(fileType);
                dto.setUrl(url);
                ret = picToParkInfoService.insertPicToBasePhoto(dto);

                aliOssResponse.setPhotoId(dto.getId());
            }


            if (ret > 0) {
                return json.setData(aliOssResponse).setCode(200).setMsg("success");
            } else {
                return json.setData(null).setCode(900).setMsg("fail");
            }

        } else {
            return json.setData(null).setCode(900).setMsg("error");
        }

    }

    @ApiOperation("删除 停车场封面、详情图")
    @PostMapping("delParkPhoto")
    public ResultJson delParkPhoto(@RequestParam String parkCode, @RequestParam int id, @RequestParam int num) {
        int ret = 0;
        if (num == 1) {
            ret = picToParkInfoService.delPhotoF(parkCode);
        }
        if (num == 2) {
            ret = picToParkInfoService.delPhotoX(id);
        }
        if (ret > 0) {
            return json.setData(ret).setCode(200).setMsg("success");
        } else {
            return json.setData(ret).setCode(900).setMsg("fail");
        }
    }


    @PostMapping("upload2")
    public ResultJson upload2(@RequestParam("file") MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        PutObjectResult putObjectResult = null;
        String imgurl="";
        try {
            String key = (String) OssAliyunUtil.getKey(prefix, FileUtils.getSuffix(file));
            InputStream f = file.getInputStream();
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(f.available());
            objectMeta.setContentType("image/jpeg");
            putObjectResult = ossClient.putObject(bucket, key, f, objectMeta);
            log.info("=={}==" + putObjectResult.getETag());

            StringBuffer sb = new StringBuffer();
            sb.append("http://").append(bucket).append(".").append(endpoint).append("/").append(key);

            imgurl = sb.toString();

        } catch (Exception oe) {
            log.error("图片上传失败,路径:" + oe);

        }

        return json.setData(putObjectResult).setMsg(imgurl);
    }


}
